package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.handUtil.SearchKeywordUtil;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import com.google.gson.JsonElement;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

;

/**
 *内容合理性
 *M-4-1
 *
 * 在M-4章节，检查募集资金用途是用于偿还银行借款，需披露“有息债务”、“短期借款”、“一年内到期的非流动负债”、“长期借款”，如果不存在提示关键词缺失；
 *
 * 预评/发行阶段
 */
@Component("R1006")
@Scope("prototype")
public class R1006 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1006.class);
    @Autowired
    private HandingData handingData;
    @Autowired
    private SearchKeywordUtil searchKeywordUtil;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1006组件M");
        List<ComponentResult> componentResults = checkRulesR1006(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1006组件BM");
        List<ComponentResult> componentResults = checkRulesR1006(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1006组件DM");
        List<ComponentResult> componentResults = checkRulesR1006(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1006组件BDM");
        List<ComponentResult> componentResults = checkRulesR1006(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle());
        return componentResults;
    }


    private List<ComponentResult> checkRulesR1006(String model,String catalogId,String chapterId,String ruleName){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;
        int pageNum = 0;
        List<ComponentResult.TextPosition> contentAndPositionList = null;
        boolean flag = false;
        int startPage = 0;
        String[] keywords = new String[]{"有息债务","短期借款","一年内到期的非流动负债","长期借款"};
        boolean isFlag = false;
        List<ComponentResult.TextPosition> chyhjkContentAndPositionList = null;
        int chyhjkPageNum = 0;

        boolean isAllErr = false;
        try {
            if (extractData!=null){
                ChapterModel chapterModel =  extractData.getChapterModel(model);
                startPage = chapterModel!=null?chapterModel.getStartPage():0;
                //偿还银行借款
                 MJZJYTType mjzjytType =null;
                if (chapterModel!=null){
                    extractItem = chapterModel.getModel("MJZJYT").getExtractItem("MJZJYT");
                    if (extractItem!=null){
                        KVText key = extractItem.getKey();
                        String text = key!=null ? key.getText():null;
                        if (StringUtils.isNotEmpty(text)&&"YHJK".equals(text)||"YXZW".equals(text)){
                            mjzjytType = MJZJYTType.valueOf(text);
                           // KVText value = null;
                            List<TextLayout> textLayouts = null;
                            switch (mjzjytType){
                                case YHJK:
                                    /*value = extractItem.getValue();
                                    chyhjkPageNum = value!=null?value.getPageNumber():startPage;
                                    chyhjkPageNum = chyhjkPageNum!=0?chyhjkPageNum:startPage;
                                    chyhjkContentAndPositionList = value!=null?getContentAndPositionList(value):null;*/
                                    textLayouts = key != null ? key.getTextLayoutList():null;
                                    chyhjkPageNum = CollectionUtils.isNotEmpty(textLayouts)?textLayouts.get(0).getPageNumber():startPage;
                                    chyhjkPageNum = chyhjkPageNum!=0?chyhjkPageNum:startPage;
                                    chyhjkContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                                    componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还银行借款","已抽取",false,getRegulationId(), chyhjkPageNum,chyhjkContentAndPositionList,"01");
                                    componentResults.add(componentResult);
                                    isFlag = true;
                                    break;
                                case YXZW:
                                    /*value = extractItem.getValue();
                                    chyhjkPageNum = value!=null?value.getPageNumber():startPage;
                                    chyhjkPageNum = chyhjkPageNum!=0?chyhjkPageNum:startPage;
                                    chyhjkContentAndPositionList = value!=null?getContentAndPositionList(value):null;*/
                                    textLayouts = key != null ? key.getTextLayoutList():null;
                                    chyhjkPageNum = CollectionUtils.isNotEmpty(textLayouts)?textLayouts.get(0).getPageNumber():startPage;
                                    chyhjkPageNum = chyhjkPageNum!=0?chyhjkPageNum:startPage;
                                    chyhjkContentAndPositionList = key!=null?getContentAndPositionList(key):null;
                                    componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还银行借款","已抽取",false,getRegulationId(), chyhjkPageNum,chyhjkContentAndPositionList,"01");
                                    componentResults.add(componentResult);
                                    isFlag = true;
                                    break;
                            }
                        }
                    }

                    if (isFlag){

                        List<PageModel> pageModelList = chapterModel.getPageModelList();
                        if (CollectionUtils.isNotEmpty(pageModelList)){

                            for (String keyword : keywords){
                                for (PageModel pageModel:pageModelList){
                                    //Map<String, Object> containsKeyWordOfRegex2Lines = handingData.isContainsKeyWord2Lines(pageModel.getJsonTextData(), keyword);
                                    Map<String, Object> containsKeyWordOfRegex2Lines = searchKeywordUtil.isContainsKeywords2LiensOfSynonyms(pageModel.getJsonTextData(), keyword,pageModel);
                                    //Map<String,Object> map =   handingData.isContainsKeyWord( pageModel.getJsonTextData(),keyword);
                                    if (containsKeyWordOfRegex2Lines!=null){
                                        flag =  (boolean)containsKeyWordOfRegex2Lines.get("flag");
                                        if (flag){
                                            pageNum = pageModel.getPageNumber();
                                            pageNum = pageNum!=0?pageNum:startPage;
                                            contentAndPositionList =  (List<ComponentResult.TextPosition>) containsKeyWordOfRegex2Lines.get("position");
                                            break;
                                        }

                                    }
                                }
                                if (flag){
                                    componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-"+keyword,"已披露",false,getRegulationId(), pageNum,contentAndPositionList,"01");
                                    componentResults.add(componentResult);
                                }else {
                                    isAllErr = true;
                                    componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-"+keyword,"缺失",true,getRegulationId(), startPage,null,"02");
                                    componentResults.add(componentResult);
                                }
                            }
                        }

                    }
                }

            }
            if (isFlag){
                if (isAllErr){
                    for (ComponentResult result : componentResults){
                        result.setExist("02");
                    }
                }
            }else {
                componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还银行借款","未识别,建议人工核对",true,getRegulationId(), startPage,contentAndPositionList,"03");
                componentResults.add(componentResult);
                for (String key :keywords){
                    componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-"+key,"未触发检查",true,getRegulationId(), startPage,contentAndPositionList,"03");
                    componentResults.add(componentResult);
                }
            }
        }catch (Exception e){
            componentResults.clear();
            componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"募集资金用途检查-偿还银行借款","未识别,建议人工核对",true,getRegulationId(), startPage,contentAndPositionList,"03");
            componentResults.add(componentResult);
            for (String key :keywords){
                componentResult =   handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-"+key,"未触发检查",true,getRegulationId(), startPage,contentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            log.error(e.getMessage(),e);
        }
        return componentResults;
    }

}
